package com.imooc.handler;

import com.imooc.exception.MyException;
import com.imooc.result.GraceJSONResult;
import com.imooc.result.ResponseStatusEnum;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.security.SignatureException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liansen
 * @create 12-23-15:01
 */
@ControllerAdvice
public class GraceExceptionHandler {

    //处理除0异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public GraceJSONResult returnArithmeticException(ArithmeticException e){
        e.printStackTrace();
        return GraceJSONResult.errorMsg(e.getMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public GraceJSONResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        e.printStackTrace();
        return GraceJSONResult.exception(ResponseStatusEnum.FILE_MAX_SIZE_500KB_ERROR);
    }

    //处理自定义异常
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public GraceJSONResult returnMyException(MyException e){
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    //处理请求参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> map = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return GraceJSONResult.errorMap(map);
    }


    //处理jwt token异常
    @ExceptionHandler({
            SignatureException.class, //签名异常
            ExpiredJwtException.class, //jwt过期异常
            UnsupportedJwtException.class, //不支持的jwt异常
            MalformedJwtException.class, //可能被篡改的jwt异常
            io.jsonwebtoken.security.SignatureException.class
    })
    @ResponseBody
    public GraceJSONResult returnSignatureException(SignatureException e){
        e.printStackTrace();
        //用户校验失败, 请重新登录
        return GraceJSONResult.exception(ResponseStatusEnum.JWT_EXPIRE_ERROR);
    }


}
